package com.qifei.xmlg_backend.filter;

import com.alibaba.fastjson.JSONObject;
import com.qifei.xmlg_backend.entity.Result;
import com.qifei.xmlg_backend.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

//import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
//import org.springframework.security.core.context.SecurityContextHolder;
//import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * JWT 过滤器：拦截所有请求，验证 Token 并把用户信息放到 SecurityContextHolder
 */
@Component
@Slf4j
public class JwtAuthenticationFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(
            HttpServletRequest request,
            HttpServletResponse response,
            FilterChain filterChain)
            throws ServletException, IOException {


        // 从 header 获取 token （也可支持 ?token=xxx）
        String authHeader = request.getHeader("token");
        if (!StringUtils.hasText(authHeader)) {
            // 尝试从header中的"token"字段获取
            authHeader = request.getHeader("token");
        }
        if (!StringUtils.hasText(authHeader)) {
            // 最后尝试从参数中获取
            authHeader = request.getParameter("token");
        }

        if (StringUtils.hasText(authHeader)) {
            String token = authHeader;
            if (token.startsWith("Bearer ")) {
                token = token.substring(7);
            }

            try {
                // 校验 JWT，解析用户名
                Claims claims = JwtUtils.parseJWT(token);
                String username = claims.get("username", String.class);
                if (username == null) {
                    username = claims.getSubject();
                }

                // 如果用户合法且上下文里还没登录，创建认证对象
                if (StringUtils.hasText(username)
                        && SecurityContextHolder.getContext().getAuthentication() == null) {

                    String role = claims.get("role", String.class); // 假设 JWT 中的 key 是 "role"
                    log.info("原始角色: " + role);
                    
                    // 创建权限列表（注意角色前缀要大写："ROLE_" 开头）
                    List<SimpleGrantedAuthority> authorities = new ArrayList<>();
                    if (StringUtils.hasText(role)) {
                        // 处理角色格式：如果是role_admin格式，转换为ROLE_ADMIN
                        String formattedRole;
                        if (role.toLowerCase().startsWith("role_")) {
                            // 去掉role_前缀，再加上ROLE_前缀
                            formattedRole = "ROLE_" + role.substring(5).toUpperCase();
                        } else {
                            formattedRole = "ROLE_" + role.toUpperCase();
                        }
                        log.info("处理后角色: " + formattedRole);
                        authorities.add(new SimpleGrantedAuthority(formattedRole));
                    }

                    UsernamePasswordAuthenticationToken authToken =
                            new UsernamePasswordAuthenticationToken(username, null, authorities);
                    authToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                    SecurityContextHolder.getContext().setAuthentication(authToken);
                }

            } catch (Exception e) {
                // Token 有问题，可选：直接返回 401
                Result res = Result.error("NOT_LOGIN");
                String json = JSONObject.toJSONString(res);
                response.setContentType("application/json;charset=utf-8");
                response.getWriter().write(json);
                return; // 拦截后面链
            }
        }

        // 放行后续 Filter / Controller
        filterChain.doFilter(request, response);
    }

}
